from redminelib import Redmine
import time

from use_mysql import UseMysql


class RedmineUse():

    def __init__(self,project_id,fixed_id,url='http://222.212.87.87:19503/',username='chencheng',password='chencheng'):
        """
        实例化的时候得到ticket的列表，其他根据方法操作ticket列表
        :param project_id: 项目的id
        :param fixed_id: 目标版本id
        :param url:
        :param username:
        :param password:
        """
        redmine = Redmine(url, username=username, password=password)
        self.issues = redmine.issue.filter(project_id=project_id,tracker_id=1,status_id='o',fixed_version_id=fixed_id)
        self.__today = time.strftime('%Y-%m-%d',time.gmtime())

    def __formatTime(self,issue,type='c'):
        """
        :param issue: 每一个ticket
        :param type: ticket是更新时间还是生成时间
        :return:
        """
        type_day = ''
        if type=='c':
            year = int(issue.created_on.year)
            month = int(issue.created_on.month)
            day = int(issue.created_on.day)
            year = '%04d' % year
            month = '%02d' % month
            day = '%02d' % day
            type_day = year + '-' + month + '-' + day
        if type =='u':
            year = int(issue.updated_on.year)
            month = int(issue.updated_on.month)
            day = int(issue.updated_on.day)
            year = '%04d' % year
            month = '%02d' % month
            day = '%02d' % day
            type_day = year + '-' + month + '-' + day
        return type_day

    def __differencetime(self, time1, time2):
        """
        计算两个时间相差的天数
        :param time1:
        :param time2:
        :return:
        """
        day1 = time.strptime(str(time1), '%Y-%m-%d')
        day2 = time.strptime(str(time2), '%Y-%m-%d')
        t = int(time.mktime(day1)) - int(time.mktime(day2))
        day_difference = abs(t // (24 * 60 * 60))
        return day_difference

    def  getTodayNewBugNum(self):
        """
        获取当天新增的ticket数量
        :return:
        """
        bugList = [['4.%s今日测试情况'%self.__today]]
        todayBugList = ['新增缺陷个数']
        num = 0
        for issue in self.issues:
            createDay = self.__formatTime(issue)
            if self.__today == createDay:
                num +=1
        todayBugList.append(num)
        bugList.append(todayBugList)
        return bugList

    def getAllBugNum(self):
        """
        获取今日的ticket总量情况
        :return:
        """
        bugList = [['5.ticket总量情况']]
        bugStatusList = ['时间','今日新建','已解决','待解决问题']
        bugNumList = []
        bugNum = 0
        newBugNum = 0
        sloveBugNum = 0
        for issue in self.issues:
            createDay = self.__formatTime(issue)
            if issue.status.name == '已解决':
                sloveBugNum += 1
            elif issue.status.name == '新建' and self.__today == createDay:
                newBugNum += 1
            else:
                bugNum += 1
        bugNumList.append(self.__today)
        bugNumList.append(newBugNum)
        bugNumList.append(sloveBugNum)
        bugNumList.append(bugNum)
        bugList.append(bugStatusList)
        bugList.append(bugNumList)
        return bugList

    def getBugStatusNum(self,bugStatusList):
        """
        获取当日ticket的不同状态的数量
        :param bugStatusList: ticket状态的列表
        :return:
        """
        bugList = []
        bugNumList = []

        for bugStatus in bugStatusList:
            bugNum = 0
            bugAllNum = 0
            if bugStatus == '时间':
                bugNumList.append(self.__today)
            else:
                for issue in self.issues:
                    if bugStatus ==  issue.status.name:
                        bugNum += 1
                    if bugStatus == '总计':
                        bugAllNum +=1
                if bugStatus == '总计':
                    bugNumList.append(bugAllNum)
                else:
                    bugNumList.append(bugNum)
        bugList.append(bugStatusList)
        bugList.append(bugNumList)
        return bugList

    def getTuiHuaGeneral(self):
        """
        退化的ticket的列表
        :return:
        """
        bugList = [['6.缺陷概况'],['退化问题列表']]
        titleList = ['序号','关系人','ticket_ID','ticket详情','状态','严重程度']
        bugList.append(titleList)
        num = 0
        for issue in self.issues:
            list1 = []
            if issue.custom_fields[3].value != '0':
                num +=1
                list1.append(num)
                list1.append(issue.assigned_to.name)
                list1.append(issue.id)
                list1.append(issue.subject)
                list1.append(issue.status.name)
                list1.append(issue.custom_fields[0].value)
                bugList.append(list1)
        return bugList

    def getGreatBug(self):
        """
        严重的ticket的列表
        :return:
        """
        bugList = [['严重问题列表']]
        titleList = ['序号', '关系人', 'ticket_ID', 'ticket详情', '状态', '严重程度']
        bugList.append(titleList)
        num = 0
        for issue in self.issues:
            list1 = []
            if issue.custom_fields[0].value in ['重大','致命']:
                num = num +1
                list1.append(num)
                list1.append(issue.assigned_to.name)
                list1.append(issue.id)
                list1.append(issue.subject)
                list1.append(issue.status.name)
                list1.append(issue.custom_fields[0].value)
                bugList.append(list1)
        return bugList

    def getBlockBug(self):
        """
        获取阻塞缺陷的列表
        :return:
        """
        bugList = [['阻塞问题列表']]
        titleList = ['序号', '关系人', 'ticket_ID', 'ticket详情', '状态', '严重程度']
        bugList.append(titleList)
        num = 0
        for issue in self.issues:
            list1 = []
            if (issue.custom_fields[0].value in ['重大','致命'] and issue.priority.name == '紧急') or issue.status.name =='阻塞':
                num = num +1
                list1.append(num)
                list1.append(issue.assigned_to.name)
                list1.append(issue.id)
                list1.append(issue.subject)
                list1.append(issue.status.name)
                list1.append(issue.custom_fields[0].value)
                bugList.append(list1)
        return bugList

    def getPersonAllBug(self,personList):
        """
        获取所有人对应的tickt
        :param personList:
        :return:
        """
        bugList = [['7.所有人缺陷对应'],['姓名','数量']]
        for person in personList:
            num = 0
            list1 = []
            for issue in self.issues:
                try:
                    if issue.assigned_to.name==person:
                        num +=1
                except Exception as e:
                    pass
            list1.append(person)
            list1.append(num)
            bugList.append(list1)
        return bugList

    def getPersonSolveBug(self,personList):
        """
        获取已解决缺陷的人员对应
        :param personList:
        :return:
        """
        bugList = [['8.已解决缺陷人员对应'],['姓名','数量']]
        for person in personList:
            num = 0
            list1 = []

            for issue in self.issues:
                try:
                    if issue.assigned_to.name == person and issue.status.name == '已解决':
                        num += 1
                except Exception as e:
                    pass
            list1.append(person)
            list1.append(num)
            bugList.append(list1)
        return bugList

    def getMoudulebug(self,mouduleList):
        """
        获取模块对应的所有ticket
        :param mouduleList:
        :return:
        """
        bugList = [['9.所有缺陷模块分布'],['模块名称','数量']]
        for moudule in mouduleList:
            num = 0
            list1 = []
            for issue in self.issues:
                try :
                    if issue.custom_fields[2].value == moudule:
                        num +=1
                except Exception as e:
                    pass
            list1.append(moudule)
            list1.append(num)
            bugList.append(list1)

        return bugList

    def getTodayBugInfo(self):
        bugList = []
        list1 = []
        tuhuiNum = 0
        greatNum = 0
        solveNum = 0
        outNum = 0
        todayNew = 0
        for issue in self.issues:
            updateDay = self.__formatTime(issue,'u')
            createDay = self.__formatTime(issue)
            if self.__differencetime(self.__today,updateDay)>7:
                outNum += 1
            if issue.status.name == '已解决':
                solveNum += 1
            if issue.custom_fields[3].value != '0':
                tuhuiNum += 1
            if issue.custom_fields[0].value in ['重大','致命']:
                greatNum += 1
            if self.__today== createDay:
                todayNew +=1

        list1.append('超过一周未更新ticket')
        list1.append(outNum)
        list1.append('退化的ticket数')
        list1.append(tuhuiNum)
        list1.append('致命/重大ticket数')
        list1.append(greatNum)
        list1.append('已解决缺陷总数')
        list1.append(solveNum)
        list1.append('今日新建ticket数')
        list1.append(todayNew)
        bugList.append(list1)
        return bugList














if __name__ =='__main__':
    db_config = {'host': '192.168.1.161',
                 'port': 3306,
                 'user': 'root',
                 'password': 'root',
                 'database': 'stats_report',
                 'charset': 'utf8'}

    re = RedmineUse(204,841)
    personList = ['何 松', '洪 学姣', '袁 凡力', '陈 铖', '佟 粤新', '刘 佳莉', '李 雪平', '肖 鸿文', '陈 洋', '邓 富桂', '沈 昕', '汪 旭雨', '颜 柯宇', '陶 建新', '李 丹', '王 雨婷', '闵 兆文']
    print(re.getPersonSolveBug(personList))
    list1=re.getAllBugNum()[-1]
    print(re.getTodayNewBugNum())
    bugStatusList = ['时间','新建','进行中','反馈','推迟','重新打开','阻塞','已解决','总计']
    print(re.getBugStatusNum(bugStatusList))
    print(re.getTuiHuaGeneral())
    my = UseMysql(db_config)
    my.insert_data(*list1)
    select_sql = "select * from bug_report"
    print(my.select_data(select_sql))
    my.close_db()










